package io.renren.modules.mapp.interceptor;

import io.renren.modules.api.annotation.AuthIgnore;
import io.renren.modules.mapp.Constants;
import io.renren.modules.mapp.entity.UserInfo;
import io.renren.modules.mapp.exception.LoginServiceException;
import io.renren.modules.mapp.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:38
 */
@Component("mappAuthorizationInterceptor")
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private LoginService loginService;

    public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AuthIgnore annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
        }else{
            return true;
        }
        //如果有@IgnoreAuth注解，则不验证token
        if(annotation != null){
            return true;
        }
        UserInfo userInfo=null;
        String id = getHeader(request,Constants.WX_HEADER_ID);
        String skey = getHeader(request,Constants.WX_HEADER_SKEY);
        userInfo=loginService.check(id,skey);

        return true;
    }
    private String getHeader(HttpServletRequest request,String key) throws LoginServiceException {
        String value = request.getHeader(key);
        if (value == null || value.isEmpty()) {
            LoginServiceException error = new LoginServiceException("INVALID_REQUEST", String.format("请求头不包含 %s，请配合客户端 SDK 使用", key));
            throw error;
        }
        return value;
    }
}
